package com.zy.baselib.adapter

import androidx.collection.SparseArrayCompat

class TypeViewDelegateManager<T> {

    private val mDelegates = SparseArrayCompat<TypeViewDelegate<T>>()

    val count: Int get() = mDelegates.size()

    fun addDelegate(delegate: TypeViewDelegate<T>) {
        val itemType = count
        mDelegates.put(itemType, delegate)
    }

    fun addDelegate(itemType: Int, delegate: TypeViewDelegate<T>) {
        mDelegates.put(itemType, delegate)
    }

    fun removeDelegate(itemType: Int) {
        mDelegates.remove(itemType)
    }

    fun getItemViewType(item: T, position: Int): Int {
        for(i in 0 until count) {
            val delegate = mDelegates.valueAt(i)
            if(delegate.isForViewType(item, position)) {
                return mDelegates.keyAt(i)
            }
        }
        throw IllegalArgumentException("No ItemViewDelegate added that matches position=${position} in data source")
    }

    fun convert(holder: ViewHolder, item: T, position: Int) {
        for(i in 0 until count) {
            val delegate = mDelegates.valueAt(i)
            if(delegate.isForViewType(item, position)) {
                delegate.convert(holder, item, position)
                return
            }
        }
        throw IllegalArgumentException("No ItemViewDelegate added that matches position=${position} in data source")
    }

    fun getItemViewLayoutId(viewType: Int) = mDelegates.get(viewType)?.getItemViewLayoutId() ?: 0

    fun getItemViewType(delegate: TypeViewDelegate<T>) = mDelegates.indexOfValue(delegate)

    fun getItemViewDelegate(viewType: Int) = mDelegates.get(viewType)!!

}